package org.wangbao.service;

import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.util.Version;
import org.wangbao.model.Block;
import org.wangbao.model.News;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class IndexBuilder {

	static String indexPath = "NewsIndex";

	Analyzer analyzer = new IKAnalyzer();
	
	File2DocumentUtils fdu = new File2DocumentUtils();

	public void createIndex(List<News> list) throws Exception {

		IndexWriter indexWriter = new IndexWriter(indexPath, analyzer, true,
				MaxFieldLength.LIMITED);

		for (int i = 0; i < list.size(); i++) {

			Document doc = fdu.saveDocument(list.get(i));
			indexWriter.addDocument(doc);

		}
		indexWriter.close();

	}

	
	public String createIndex(News news) throws Exception {

		IndexWriter indexWriter = new IndexWriter(indexPath, analyzer, true,
				MaxFieldLength.LIMITED);

		Document doc = fdu.saveDocument(news);
		
		indexWriter.addDocument(doc);
		indexWriter.close();
		return doc.get("sensitive");

	}

	public String search() throws Exception {

		String queryString = "台独";
		StringBuffer sb = new StringBuffer();

		String[] fields = { "title", "content" };
		QueryParser queryParser = new MultiFieldQueryParser(Version.LUCENE_29,
				fields, analyzer);
		Query query = queryParser.parse(queryString);

		IndexSearcher indexSearcher = new IndexSearcher(indexPath);
		Filter filter = null;
		TopDocs topDocs = indexSearcher.search(query, filter, 1000);
		System.out.println("总共有【" + topDocs.totalHits + "】条匹配结果");

		for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
			int docSn = scoreDoc.doc; // 文档内部编号
			Document doc = indexSearcher.doc(docSn); // 根据编号取出相应的文档
			// File2DocumentUtils.printDocumentInfo(doc); // 打印出文档信息
			sb.append(File2DocumentUtils.printJsonInfo(doc));

		}
		return sb.toString();
	}

}
